<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
import { useCodeStore } from "@/stores/code.js";
import picView from "../../components/pic/index.vue";
import {
  appCategory,
  supplierSelector,
  productCreate,
  appProductDetail,
  appProductDisable,
  appProductEnable,
  productUpdate,
  appProductCode,
  appUnit,
} from "@/services/goods";
import { base_URL } from "@/utils/http";
import homeStart from "@/pages/goods/static/sacd.png";

const showSelect = ref("");

if (uni.getStorageSync("selectShopType")) {
  showSelect.value = uni.getStorageSync("selectShopType");
}

// import tabbarView from "../components/tabbar.vue";
const codeStore = useCodeStore();

console.log("codeStore", codeStore.code);

const formMode = ref(null);
const form = ref({
  barCode: "",
  name: "",
  categoryId: "",
  image: "",
  stock: "",
  salePrice: "",
  purchasePrice: "",
  storePricing: false,
  wholePrice: "",
  salesType: "",

  skuCode: "",
  unit: "",
  supplierId: "",
  memberPrice: "",
  supplierName: "",
  valuationType: 0,
  barCodeList: [],
  remark: "",

  //、
  username: "",
  password: "",
  categoryName: "",
  price: "",
  ol_price: "",
});
const checked = ref(false);
const showBarCode = ref(false);
//类型
const type = ref("");
// id
const id = ref("");
const barCodeStr = ref("");

onLoad((options) => {
  console.log(options);
  type.value = options.type ? options.type : "";
  id.value = options.id ? options.id : "";
  if (id.value) {
    getProduceDet();
  }
  codeStore.setcode("");
  getAppUnit();
  getAppCategory();
});

onShow(() => {
  if (codeStore.code) {
    if (showBarCode.value) {
      selectBarCodeItem.value = codeStore.code;
    } else {
      form.value.barCode = codeStore.code;

      if (type.value != "add") {
        form.value.barCodeList[0] = codeStore.code;
      }
    }
  }

  // showToast("扫码结果" + codeStore.code);
});
//商品单位
const unitList = ref([]);
const getAppUnit = () => {
  appUnit({}).then((res) => {
    console.log(res);
    unitList.value = [res.data];

    console.log(unitList.value);
  });
};
const getAppCategory = async () => {
  try {
    let res = await appCategory();

    let arr = [];
    let newArr = [];
    let newArr2 = [];

    res.data.forEach((item, index) => {
      if (!item.parentId) {
        arr.push({ ...item, select: false, children: [] });
      } else {
        newArr.push({ ...item });
      }
    });
    arr.forEach((item, index) => {
      newArr.forEach((item2, index2) => {
        if (item.id == item2.parentId) {
          // item2.children = item.children || [];

          item.children.push({ ...item2, select: false, children: [] });
          newArr.splice(index2, 1);
        }
      });
    });
    arr.forEach((item, index) => {
      item.children.forEach((element, index) => {
        newArr.forEach((item2, index2) => {
          if (element.id == item2.parentId) {
            element.children.push({ ...item2, select: false });
          }
        });
      });
    });
    pickerArr.value = arr;
    columns.value[0] = arr;
    columns.value[1] = arr[0].children;
    columns.value[2] = arr[0].children[0].children;
    console.log(columns.value);
    // columns.value = arr;
  } catch (e) {}
};

//单选
const onRadioChangeFun = (e) => {
  console.log(e);
  if (e == 1) {
    checked.value = true;
  } else {
    checked.value = false;
  }
};

//商品详情
const getProduceDet = async () => {
  console.log(id.value);
  try {
    let res = await appProductDetail({ id: id.value });
    if (res.code == 200) {
      form.value = res.data;
      fileList.value = [{ url: res.data.image }];
      form.value.checked = res.data.memberPrice > 0 ? true : false;
      purchasePricevalue.value = res.data.purchasePrice;
      checked.value = form.value.barCodeList > 0 ? true : false;
      form.value.barCodeList = form.value.barCodeList
        ? form.value.barCodeList
        : [];
      barCodeStr.value = res.data.barCode;
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
    }
  } catch (e) {
    // uni.showToast({
    //   title: e.msg,
    //   icon: "none",
    // });
  }
};

const pageslenght = ref(0);
onMounted(() => {
  getSupplierSelector();
});
const fileList = ref([]);

// const columns = ref([]);
const showPicker = ref(false);
const showUnitPicker = ref(false);
const pickerValue = ref([]);
const purchasePricevalue = ref(0);

const onCareConfirm = ({ selectedValues, selectedOptions }) => {
  console.log(selectedValues, selectedOptions);
  form.value.categoryName = selectedOptions[selectedOptions.length - 1]?.name;
  form.value.categoryId = selectedValues[selectedValues.length - 1];

  pickerValue.value = selectedValues;
  showPicker.value = false;
};
const scanCode = async () => {
  try {
    let res = await appProductCode();
    console.log(res);
    if (res.code == 200) {
      form.value.barCode = res.data.code;
      if (type.value != "add") {
        form.value.barCodeList[0] = res.data.code;
      }
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
    }
  } catch (error) {}
};

const ishowcamera = ref(false);
const shaScanCode = () => {
  // #ifdef APP-PLUS
  // 允许从相机和相册扫码
  const systemInfo = uni.getSystemInfoSync();
  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else {
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);

              uni.scanCode({
                scanType: ["barCode", "qrCode"],
                autoDecodeCharset: true,
                autoZoom: true,
                success: function (res) {
                  console.log("条码类型：" + res.scanType);
                  console.log("条码内容：" + res.result);
                  form.value.barCode = res.result;
                },
              });
            }
          }
        );
      }
    });
    return;
  }
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    autoZoom: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      form.value.barCode = res.result;
    },
  });

  // #endif
  console.log("扫码");
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index" });
  // #endif

  codeStore.setcode("");
};

const confirmAfterRead = (vla) => {
  fileList.value = [{ url: vla }];
  console.log(fileList.value);
};
const deleteImg = (index) => {
  fileList.value.splice(index, 1);
  console.log(fileList.value);
};

const saveFun = () => {
  console.log("保存");
  console.log(form.value);
  // console.log(fileList.value[0].content);
  formMode.value.submit();
};

//image 上传
const isUp = ref(false);
const deleteFile = (e) => {
  form.value.image = "";
};
const failedFun = (E) => {
  uni.showToast({
    title: E.errors[0].message,
    icon: "none",
  });
};
const onSubmit = async (values) => {
  if (!form.value.salesType) {
    return uni.showToast({
      title: "请选择是否寄售商品",
      icon: "none",
    });
  }
  if (!form.value.salePrice) {
    return uni.showToast({
      title: "请输入售价",
      icon: "none",
    });
  }
  if (form.value.salePrice <= 0) {
    return uni.showToast({
      title: "请输入售价大于0",
      icon: "none",
    });
  }

  if (!fileList.value > 0) {
    form.value.image = "";
  }
  fileList.value.forEach((item) => {
    form.value.image = item.url;
  });

  console.log(form.value.image);

  // if (fileList.value.length > 0) {
  //   console.log(fileList.value);
  //   let flie = fileList.value[0].file;

  //   const formData = new FormData();
  //   formData.append("file", flie);
  //   console.log(flie, "flie", flie.path);
  // }
  console.log(form.value.checked);
  if (!form.value.checked) {
    form.value.memberPrice = 0;
  } else {
  }
  if (!checked.value) {
    form.value.barCode = "";
    if (form.value.barCodeList.length > 0) {
      form.value.barCodeList = [];
    }
  } else {
  }

  if (type.value == "add") {
    try {
      let res = await productCreate(form.value);
      console.log(res);
      if (res.code == 200) {
        // showToast("添加成功");
        uni.showToast({
          title: "添加成功",
          icon: "none",
        });
        uni.navigateBack();
      } else {
        // showToast(res.msg);
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    } catch (e) {
      // showToast(e.msg);
      uni.showToast({
        title: e.msg,
        icon: "none",
      });
    }
  } else {
    form.value.barCode = form.value.barCodeList;
    barCodeStr.value = form.value.barCodeList.join(",");
    // delete form.value.barCodeList;
    if (!checked.value) {
      form.value.barCode = [];
    } else {
    }

    try {
      let res = await productUpdate(form.value);
      console.log(res);
      if (res.code == 200) {
        // showToast("修改成功");
        uni.showToast({
          title: "修改成功",
          icon: "none",
        });

        uni.navigateBack();
      } else {
        // showToast(res.msg);
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    } catch (e) {
      // showToast(e.msg);
      uni.showToast({
        title: e.msg,
        icon: "none",
      });
    }
  }
};
async function base64ToTempFilePath(base64Data) {
  const fs = uni.getFileSystemManager();
  const fileName = "LotteryActivity_" + Date.now() + ".png"; // 自定义文件名，可根据需要修改
  console.log("23234324", uni.env);
  const filePath = uni.env.USER_DATA_PATH + "/" + fileName;
  console.log("232343245");
  const base64 = base64Data.split(",")[1]; //移除固定头部
  const buffer = uni.base64ToArrayBuffer(base64);
  let promise = await new Promise((resolve, reject) => {
    fs.writeFile({
      filePath,
      data: buffer,
      encoding: "binary",
      success(res) {
        resolve(filePath); // fulfilled
      },
      fail(err) {
        reject(err); // rejected
      },
    });
  });
  return promise;
}

//金额校验
const validator = (val) => {
  let arr = /^\d+(\.\d{1,2})?$/.test(val);
  console.log(arr, val);
  return arr;
};
//金额校验
const validatortwo = (val) => {
  let arr = /^\d+(\.\d{1,2})?$/.test(val);
  console.log(arr, val);

  if (!val) {
    return true;
  } else {
    return arr;
  }
};

//商品分类
const categoryList = ref([]);
const customFieldName = ref({
  text: "name",
  value: "id",
  children: "children",
});

const columns = ref([[], [], []]);

const pickershow = ref(false);
const pickerArr = ref([]);

//获取供应商
const supplierList = ref([]);
const supplierFieldName = ref({
  text: "name",
  value: "id",
  children: "children",
});
// const columns = ref([]);
const supplierPicker = ref(false);
const supplierValue = ref([]);
const pickerUnitValue = ref([]);
const supplierUnitName = ref({
  text: "name",
  value: "id",
  children: "children",
});

const getSupplierSelector = async () => {
  try {
    let res = await supplierSelector({ pageIndex: 1, pageSize: 999 });
    supplierList.value = res.data.datas;
  } catch (e) {}
};

const onSupplierCareConfirm = ({ selectedValues, selectedOptions }) => {
  console.log(selectedValues, selectedOptions);
  form.value.supplierName = selectedOptions[0]?.name;
  form.value.supplierId = selectedValues[0];
  supplierValue.value = selectedValues;
  supplierPicker.value = false;
};
const onCareUnitConfirm = ({ selectedValues, selectedOptions }) => {
  console.log(selectedValues, selectedOptions);
  form.value.unit = selectedOptions[0]?.name;
  // form.value.unit = selectedValues[0];
  pickerUnitValue.value = selectedValues;
  showUnitPicker.value = false;
};
const onSwitchChange = (e) => {
  console.log(e);
  if (e) {
    purchasePricevalue.value = form.value.purchasePrice;
  } else {
    purchasePricevalue.value = 0;
  }
};

//商品禁用
const availableFun = async (item) => {
  if (item) {
    try {
      let res = await appProductDisable({ id: form.value.id });
      if (res.code == 200) {
        form.value.available = !form.value.available;
        // showToast("禁用成功");
        uni.showToast({
          title: "禁用成功",
          icon: "none",
        });
        uni.reLaunch({ url: "/pages/goods/goods_list/index" });
      } else {
        uni.showToast({
          title: "禁用成功",
          icon: "none",
        });
      }
    } catch (e) {
      uni.showToast({
        title: e.msg,
        icon: "none",
      });
    }
  } else {
    try {
      let res = await appProductEnable({ id: form.value.id });
      if (res.code == 200) {
        form.value.available = !form.value.available;
        uni.showToast({
          title: "启用成功",
          icon: "none",
        });
      } else {
        uni.showToast({
          title: "启用失败",
          icon: "none",
        });
      }
    } catch (e) {
      uni.showToast({
        title: e.msg,
        icon: "none",
      });
    }
  }
};

const selectBarCodeItem = ref("");
const selectBarCodeindex = ref("");
const isnewBarCode = ref(false);
const showBarCodeFun = (item, index) => {
  isnewBarCode.value = false;
  showBarCode.value = true;
  selectBarCodeItem.value = item;
  selectBarCodeindex.value = index;
};
const scanCodeTwo = async () => {
  console.log("生成");
  try {
    let res = await appProductCode();
    console.log(res);
    if (res.code == 200) {
      // form.value.barCode = res.data.code;
      selectBarCodeItem.value = res.data.code;
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
    }
  } catch (error) {}
};
const addBarCodeItem = () => {
  if (selectBarCodeindex.value == 0) {
    form.value.barCode = selectBarCodeItem.value;
  }
  form.value.barCodeList[selectBarCodeindex.value] = selectBarCodeItem.value;
  showBarCode.value = false;
  checked.value = true;
  barCodeStr.value = form.value.barCodeList.join(",");
  console.log(form.value.barCodeList);
  codeStore.setcode("");
};

const addBarCode = () => {
  isnewBarCode.value = true;
  selectBarCodeItem.value = "";
  selectBarCodeindex.value = form.value.barCodeList.length;
  showBarCode.value = true;
};
const delBarCodeFun = () => {
  form.value.barCodeList.splice(selectBarCodeindex.value, 1);

  showBarCode.value = false;
  console.log("删除");
};

const rules = ref({
  name: {
    type: "string",
    required: true,
    message: "请填写商品名称",
    trigger: ["blur", "change"],
  },
});

const uUpload = ref(null);
// 删除图片
const deletePic = (event) => {
  fileList.value = [];
  this.form.image = "";
};
const afterRead = async (event, type) => {
  console.log(event);
  let fileListLen = 0;
  let filelist = [];
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式

  fileListLen = fileList.value.length;
  filelist = fileList.value;

  let lists = [].concat(event.file);
  lists.map((item) => {
    filelist.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });

  // return;
  for (let i = 0; i < lists.length; i++) {
    uni.uploadFile({
      url: base_URL + "/app/product/image",
      filePath: lists[i].url,
      name: "file",
      formData: {
        user: "test",
      },
      header: {
        "X-Auth-Token": uni.getStorageSync("X-Auth-Token"),
      },
      success: async (uploadFileRes) => {
        let data = JSON.parse(uploadFileRes.data);
        if (data.code == 200) {
          filelist.splice(fileListLen, 1, {
            ...item,
            status: "success",
            message: "",
            url: data.data.url,
          });
          fileListLen++;
        } else {
          filelist.value = [];
          lists = [];
          console.log(data, filelist.value);
          uUpload.value.chooseFile();
          uni.showToast({
            title: data.msg,
            icon: "none",
          });
        }
      },
      fail: function (e) {
        console.log(e);
        filelist.value = [];
        lists = [];
        uni.showToast({
          title: e.msg,
          icon: "none",
        });
        uni.hideLoading();
      },
    });

    let item = fileList.value[fileListLen];
  }
};

// 监听省市区列表选择器变化
const distChangeHandler = (item) => {
  const { columnIndex, value } = item;
  console.log(columnIndex, value);
  let city = value[0].children;
  if (columnIndex === 0) {
    // 省变化更新市、区列表
    // setColumnValues(index, setVal) 设置对应列的选择值

    columns.value[1] = value[0].children;
    columns.value[2] = value[0].children[0].children;
    // uPickerRef.value.setColumnValues(1, city);
    // uPickerRef.value.setColumnValues(2, city[0].children);
  } else if (columnIndex === 1) {
    // 市变化更新区/县列表
    // uPickerRef.value.setColumnValues(2, value[1].children);
    columns.value[2] = value[1].children;
  }
};

// 确定选择服务地区
const confirmDist = (item) => {
  const { value } = item;
  console.log(value);
  form.value.categoryName = `${value[2].name}`;
  form.value.categoryId = `${value[2].id}`;
  //  form.categoryName = `${value[0].name} / ${value[1].name} / ${value[2].name}`;
  pickershow.value = false; // 关闭弹框
};
const confirmUnitDist = (item) => {
  const { value } = item;
  console.log(value);
  form.value.unit = `${value[0].name}`;
  //  form.categoryName = `${value[0].name} / ${value[1].name} / ${value[2].name}`;
  showUnitPicker.value = false; // 关闭弹框
};

const confirmGDist = (item) => {
  const { value } = item;
  console.log(value);
  form.value.supplierName = `${value[0].name}`;
  form.value.supplierId = `${value[0].id}`;
  //  form.categoryName = `${value[0].name} / ${value[1].name} / ${value[2].name}`;
  supplierPicker.value = false; // 关闭弹框
};
const showBarCodeclose = () => {
  showBarCode.value = false;
};

// 取消服务地区选择
const distCancel = () => {
  pickershow.value = false;
};

const groupChange = (e) => {
  console.log("groupChange", e);
  if (e == 1) {
    checked.value = true;
  }
};

//无网络

const connected = () => {
  if (id.value) {
    getProduceDet();
  }
  codeStore.setcode("");
  getAppUnit();
  getAppCategory();
};
</script>

<template>
  <topNav
    :title="type == 'add' ? '新增商品' : '编辑商品'"
    @save="saveFun"
    rType="save"
  ></topNav>
  <view class="goods_form">
    <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
    <up-form
      labelPosition="left"
      labelWidth="180rpx"
      :model="form"
      :rules="rules"
      ref="form1"
    >
      <view style="padding: 0 30rpx">
        <up-form-item
          :required="true"
          label="寄售商品"
          prop="salesType"
          borderBottom
          ref="item1"
        >
          <up-radio-group v-model="form.salesType" v-if="type == 'add'">
            <up-radio
              :customStyle="{}"
              label="是(先售后结)"
              :name="2"
            ></up-radio>
            <up-radio
              :customStyle="{ marginLeft: '20rpx' }"
              :name="1"
              label="否"
            >
            </up-radio>
          </up-radio-group>
          <text style="color: #c8c9cc" v-if="type != 'add'">{{
            form.salesType == 2 ? "寄售" : form.salesType == 1 ? "非寄售" : ""
          }}</text>
        </up-form-item>
        <view class="line_in"></view>
        <up-form-item
          :required="true"
          label="商品名称"
          prop="name"
          borderBottom
          ref="item1"
        >
          <up-input
            v-model="form.name"
            border="none"
            placeholder="请填写商品名称"
          ></up-input>
        </up-form-item>
        <view class="line_in"></view>
        <up-form-item label="商品主图" prop="fileList" borderBottom ref="item1">
          <view style="width: 100%">
            <picView
              :fileList="fileList"
              @confirmFun="confirmAfterRead"
              @delete="deleteImg"
            ></picView>
          </view>
          <!-- <up-upload
            :fileList="fileList"
            @afterRead="afterRead"
            @delete="deletePic"
            name="1"
            multiple
            ref="uUpload"
            accept="image"
            :previewFullImage="true"
            :maxCount="1"
          ></up-upload> -->
        </up-form-item>
        <view class="line_in"></view>
        <up-form-item
          :required="true"
          label="归属分类"
          prop="categoryName"
          borderBottom
          ref="item1"
        >
          <view
            class="categoryName-select"
            :class="form.categoryName ? 'categoryName' : ''"
            @click="pickershow = true"
            >{{ form.categoryName ? form.categoryName : "点击选择" }}
          </view>

          <template #right>
            <up-icon name="arrow-right" @click="pickershow = true"></up-icon>
          </template>
        </up-form-item>
        <view class="line_in"></view>

        <up-form-item
          :required="true"
          label="计价方式"
          prop="valuationType"
          borderBottom
          ref="item1"
          v-if="type == 'add'"
        >
          <up-radio-group v-model="form.valuationType" @change="groupChange">
            <up-radio :customStyle="{}" label="称重kg" :name="0"></up-radio>
            <up-radio
              :customStyle="{ marginLeft: '20rpx' }"
              :name="1"
              label="计件"
            >
            </up-radio>
          </up-radio-group>

          <!-- <view
          class="categoryName-select"
          :class="form.categoryName ? 'categoryName' : ''"
          @click="pickershow = true"
          >{{ form.categoryName ? form.categoryName : "点击选择" }}
        </view> -->
        </up-form-item>
        <view class="line_in" v-if="type == 'add'"></view>
        <up-form-item
          :required="true"
          label="计价方式"
          prop="valuationType"
          borderBottom
          ref="item1"
          v-if="type != 'add'"
        >
          <text style="color: #c8c9cc">{{
            form.valuationType == 1
              ? "计件"
              : form.valuationType == 2
              ? "定重(kg)"
              : "称重(kg)"
          }}</text>

          <template #right>
            <text style="color: #c8c9cc">(不可修改)</text>
          </template>
        </up-form-item>
        <!-- <view class="line_in"></view> -->

        <view
          class="line_in"
          v-if="type != 'add' && form.dhCode && form.productType == 1"
        ></view>
        <up-form-item
          v-if="type != 'add' && form.dhCode && form.productType == 1"
          :required="true"
          label="称码"
          prop="dhCode"
          borderBottom
          ref="item1"
        >
          <text style="color: #c8c9cc">{{ form.dhCode }}</text>

          <template #right>
            <text style="color: #c8c9cc">(不可修改)</text>
          </template>
        </up-form-item>
        <view
          class="line_in"
          v-if="type != 'add' && form.valuationType != 0"
        ></view>

        <up-form-item
          :required="true"
          label="是否有条码"
          prop="checked"
          borderBottom
          ref="item1"
          v-if="form.valuationType != 0"
        >
          <template #right>
            <up-switch
              space="2"
              v-model="checked"
              activeColor="#00B42A"
              inactiveColor="rgb(230, 230, 230)"
            >
            </up-switch>
          </template>
        </up-form-item>
        <view class="line_in" v-if="form.valuationType != 0"></view>

        <up-form-item
          :required="true"
          v-if="type == 'add' && checked && form.valuationType != 0"
          label="条码"
          prop="barCode"
          borderBottom
          ref="item1"
        >
          <up-input
            v-model="form.barCode"
            disabledColor="#ffffff"
            placeholder="请输入条码"
            border="none"
          ></up-input>

          <template #right>
            <view class="botton-right"
              ><view class="botton-in" @click="scanCode">生成</view>
              <view class="input-h"></view>
              <up-icon
                name="scan"
                @click="shaScanCode"
                color="#1679fb"
                size="38rpx"
              ></up-icon>
            </view>
          </template>
        </up-form-item>
        <view
          class="line_in"
          v-if="type == 'add' && checked && form.valuationType != 0"
        ></view>
        <up-form-item
          :required="true"
          v-if="type != 'add' && barCodeStr"
          label="条码"
          prop="barCode"
          borderBottom
          ref="item1"
        >
          <up-input
            v-model="form.barCodeList[0]"
            disabledColor="#ffffff"
            placeholder="请输入条码"
            border="none"
          ></up-input>

          <template #right>
            <view class="botton-right"
              ><view class="botton-in" @click="scanCode">生成</view>
              <view class="input-h"></view>
              <up-icon
                name="scan"
                @click="shaScanCode"
                color="#1679fb"
                size="38rpx"
              ></up-icon>
            </view>
          </template>
          <!-- <text style="color: #c8c9cc">{{
            type != "add" ? barCodeStr : form.barCode
          }}</text> -->
        </up-form-item>
        <view class="line_in" v-if="type != 'add'"></view>
        <up-form-item
          :required="true"
          label="商品售价"
          prop="salePrice"
          borderBottom
          ref="item1"
        >
          <up-input
            v-if="type == 'add'"
            type="digit"
            v-model="form.salePrice"
            border="none"
            placeholder="请填写商品售价"
          >
            <template #prefix>
              <text>¥</text>
            </template></up-input
          >
          <view
            v-if="type != 'add'"
            class="categoryName-select categoryName"
            style="color: rgb(200, 201, 204)"
            ><text>¥</text>{{ form.salePrice }}
          </view>
        </up-form-item>
        <view class="line_in"></view>
        <up-form-item
          label="商品进价"
          prop="purchasePrice"
          borderBottom
          ref="item1"
        >
          <up-input
            type="digit"
            v-model="form.purchasePrice"
            border="none"
            placeholder="请填写商品进价"
          >
            <template #prefix>
              <text>¥</text>
            </template></up-input
          >
        </up-form-item>
        <view class="line_in"></view>
        <up-form-item label="批发价" prop="wholePrice" borderBottom ref="item1">
          <up-input
            type="digit"
            v-model="form.wholePrice"
            border="none"
            placeholder="请填写批发价"
          >
            <template #prefix>
              <text>¥</text>
            </template>
          </up-input>
        </up-form-item>
        <view class="line_in"></view>
        <up-form-item label="单位" prop="unit" borderBottom ref="item1">
          <view
            class="categoryName-select"
            :class="form.unit ? 'categoryName' : ''"
            @click="showUnitPicker = true"
            >{{ form.unit ? form.unit : "点击选择" }}
          </view>

          <template #right>
            <up-icon
              name="arrow-right"
              @click="showUnitPicker = true"
            ></up-icon>
          </template>
        </up-form-item>
      </view>
      <view
        class="line_in"
        style="height: 20rpx; background-color: #f5f5f5"
      ></view>
      <view style="padding: 0 30rpx">
        <up-form-item
          label="供应商"
          prop="supplierName"
          borderBottom
          ref="item1"
        >
          <view
            class="categoryName-select"
            :class="form.supplierName ? 'categoryName' : ''"
            @click="supplierPicker = true"
            >{{ form.supplierName ? form.supplierName : "点击选择" }}
          </view>

          <template #right>
            <up-icon
              name="arrow-right"
              @click="supplierPicker = true"
            ></up-icon>
          </template>
        </up-form-item>
        <view class="line_in"></view>
        <up-form-item label="会员价" prop="checked" borderBottom ref="item1">
          <up-input
            v-if="form.checked"
            type="digit"
            v-model="form.memberPrice"
            border="none"
            placeholder="请填写会员价"
          ></up-input>
          <template #right>
            <up-switch
              size="20"
              space="2"
              v-model="form.checked"
              activeColor="#00B42A"
              inactiveColor="rgb(230, 230, 230)"
            >
            </up-switch>
          </template>
        </up-form-item>
        <view class="line_in"></view>
        <up-form-item
          label="门店自定价"
          prop="storePricing"
          borderBottom
          ref="item1"
        >
          <template #right>
            <up-switch
              space="2"
              size="20"
              v-model="form.storePricing"
              activeColor="#00B42A"
              inactiveColor="rgb(230, 230, 230)"
            >
            </up-switch>
          </template>
        </up-form-item>
      </view>
      <view
        class="line_in"
        style="height: 20rpx; background-color: #f5f5f5"
      ></view>
      <view style="padding: 0 30rpx">
        <up-form-item label="说明" prop="remark" borderBottom ref="item1">
          <up-textarea
            v-model="form.remark"
            placeholder="请输入内容"
            autoHeight
          ></up-textarea>
        </up-form-item>
        <!-- <up-form-item
          v-for="(item1, index1) in form.barCodeList"
          :key="index1"
          v-if="type != 'add'"
          :label="'商品条码' + (index1 + 1)"
          :prop="'barCode' + (index1 + 1)"
          borderBottom
          ref="item1"
          @click="showBarCodeFun(item1, index1)"
        >
          <view class="categoryName-select categoryName">{{ item1 }} </view>
          
        </up-form-item> -->
      </view>
    </up-form>
  </view>
  <!-- <view class="add-barCode" @click="addBarCode" v-if="type != 'add'">
    <van-button type="default" class="botton-to" @click="addBarCode()">
      {{ "添加一品多码商品" }}
    </van-button>
  </view> -->

  <div class="foot-btn">
    <view class="foot-btn-k"
      ><van-button block type="primary" @click="onSubmit(form)">
        {{ type == "add" ? "保存" : "保存" }}
      </van-button></view
    >
  </div>

  <view
    class="botton-bt"
    v-if="type != 'add' && showSelect == 'admin'"
    v-permission="['manager:product:disable']"
  >
    <van-button
      type="default"
      class="botton-to"
      @click="availableFun(form.available)"
    >
      {{ form.available ? "禁用此商品" : "启用此商品" }}
    </van-button>
  </view>

  <view
    class="botton-bt"
    v-if="type != 'add' && showSelect == 'shop'"
    v-permission="['manager:product:disable']"
  >
    <van-button
      type="default"
      class="botton-to"
      @click="availableFun(form.available)"
    >
      {{ form.available ? "禁用此商品" : "启用此商品" }}
    </van-button>
  </view>

  <view style="height: 200rpx; width: 100%"></view>

  <!-- <van-popup v-model:show="supplierPicker" destroy-on-close position="bottom">
    <van-picker
      :model-value="supplierValue"
      :columns="supplierList"
      :columns-field-names="supplierFieldName"
      @confirm="onSupplierCareConfirm"
      @cancel="supplierPicker = false"
    />
  </van-popup> -->
  <!-- 
  <van-popup v-model:show="showUnitPicker" destroy-on-close position="bottom">
    <van-picker
      :columns="unitList"
      :model-value="pickerUnitValue"
      :columns-field-names="supplierUnitName"
      @confirm="onCareUnitConfirm"
      @cancel="showUnitPicker = false"
    />
  </van-popup> -->
  <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
    <van-picker
      :model-value="pickerValue"
      :columns="columns"
      :columns-field-names="customFieldName"
      @confirm="onCareConfirm"
      @cancel="showPicker = false"
    />
  </van-popup>
  <up-popup
    :show="showBarCode"
    destroy-on-close
    position="bottom"
    :round="true"
    :closeable="true"
    @close="showBarCodeclose"
    :safe-area-inset-bottom="true"
  >
    <view class="add-popup">
      <view class="title">一品多码</view>
      <view class="title-des">一个商品对应多个条码</view>
      <view class="top-hx"></view>
      <view class="add-barcode-input">
        <view class="add-barcode-input-icon">
          <image src="../../../static/goods/code.png" mode="scaleToFill" />
        </view>
        <van-field
          v-model="selectBarCodeItem"
          name="barCodes"
          label="条码"
          placeholder="输入条码"
        >
          <template #button>
            <view class="botton-right"
              ><view class="botton-in" @click="scanCodeTwo">生成</view>
              <view class="input-h"></view
              ><van-icon
                @click="shaScanCode"
                color="#1679fb"
                size="32rpx"
                name="scan"
            /></view>
          </template> </van-field
      ></view>
      <view class="bt-hx"></view>

      <view class="foods_bt">
        <van-button
          class="qx-bt"
          type="default"
          @click="delBarCodeFun"
          v-if="isnewBarCode == false"
          >删除</van-button
        >
        <van-button
          class="qx-bt"
          type="default"
          @click="showBarCode = false"
          v-if="isnewBarCode"
          >关闭</van-button
        >
        <van-button class="qr-bt" @click="addBarCodeItem" type="primary"
          >确认</van-button
        >
      </view>
    </view>
  </up-popup>

  <up-picker
    :show="pickershow"
    ref="uPickerRef"
    :columns="columns"
    keyName="name"
    @confirm="confirmDist"
    @change="distChangeHandler"
    @cancel="distCancel"
  >
  </up-picker>
  <up-picker
    :show="showUnitPicker"
    ref="uPickerRef"
    :columns="unitList"
    keyName="name"
    @confirm="confirmUnitDist"
    @cancel="showUnitPicker = false"
  >
  </up-picker>

  <up-picker
    :show="supplierPicker"
    ref="uPickerRef"
    :columns="[supplierList]"
    keyName="name"
    @confirm="confirmGDist"
    @cancel="supplierPicker = false"
  >
  </up-picker>
  <view class="show-camera" v-if="ishowcamera">
    <view class="show-camera-k">
      <view class="show-sm"> 设备权限使用说明 </view>
      <view class="show-des">
        为了给您带来更好的服务，需要获取您的相机权限与读取图片及文件权限，用于更换上传图片、扫一扫等功能，对于您授权的信息我们竭尽全力提供安全保护。
      </view>
    </view>
  </view>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
